package middleware

import (
	"govue3/utils"
	"log"
	"net/http"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
)

// JWTAuth 中间件：包含自动刷新令牌逻辑
func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 排除不需要认证的路由
		if c.Request.URL.Path == "/api/v1/login" || c.Request.URL.Path == "/api/v1/register" {
			c.Next()
			return
		}

		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				"error": "未提供认证信息",
			})
			return
		}

		// 解析 Bearer Token
		parts := strings.SplitN(authHeader, " ", 2)
		if len(parts) != 2 || parts[0] != "Bearer" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				"error": "认证信息格式错误",
			})
			return
		}

		token := parts[1]
		claims, err := utils.ParseToken(token)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
				"error": "无效的认证信息",
			})
			return
		}

		// 检查令牌剩余时间，触发自动刷新
		refreshThreshold := 5 * time.Minute // 剩余时间小于5分钟时触发刷新
		now := time.Now().Unix()
		expiration := claims.ExpiresAt // 需确保claims包含ExpiresAt字段（见utils的ParseToken实现）
		timeRemaining := expiration - now
		if timeRemaining > 0 && timeRemaining < int64(refreshThreshold.Seconds()) {
			// 生成新令牌
			newToken, err := utils.RefreshToken(token)
			if err == nil {
				// 将新令牌写入响应头
				c.Header("X-New-Token", newToken)
			} else {
				// 记录错误但继续处理请求
				log.Println("刷新令牌失败:", err)
			}
		}

		// 将用户ID存入上下文
		c.Set("user_id", claims.UserID)
		c.Next()
	}
}
